﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Hartley.ApplicationLogic;
using Hartley.DTOs;
using Hartley.Util;

namespace WebApplication1
{
    public partial class viewAllAthleticDataAsGrid : System.Web.UI.Page
    {
        protected int currentPageNumber = 1;
        private const int PAGE_SIZE = 10;
        List<AthleticDataDTO> allAthleticData;
        string queryString;
        AthleticAL athleticAL;
        SportsUtil sportsUtil;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                BindData();

            }
        }

        private void BindData()
        {

            athleticAL = new AthleticAL();
            sportsUtil = new SportsUtil();
            allAthleticData = new List<AthleticDataDTO>();
            List<AthleticDataDTO> allAthleticDataOfOnePage = new List<AthleticDataDTO>();

            queryString = Request.QueryString.ToString();
            string afterRemovedPlusSign = "";
            string afterReplaceComma = "";
            string correctedQueryString = "";
            string selectedCategory = "";

            
            int selectdYr;
            bool convertableToInteger = Int32.TryParse(queryString, out selectdYr);

            if (convertableToInteger)
            {
                allAthleticData = athleticAL.GetAthleticDataByYearByLevelByAgeGruopByEvent(selectdYr, "", "", "").ToList();
                selectedCategory = "Year";
            }
            else
            {
                allAthleticData =athleticAL.GetAllAthleticData();
            }

            if (queryString.Contains('+'))
            {
                afterRemovedPlusSign = queryString.Replace('+', ' ');
            }
            else
            {
                afterRemovedPlusSign = queryString;
            }

            if (afterRemovedPlusSign.Contains("%2c"))
            {
                afterReplaceComma = afterRemovedPlusSign.Replace("%2c", ",");
            }
            else
            {
                afterReplaceComma = afterRemovedPlusSign;
            }
            correctedQueryString = afterReplaceComma;
            List<AthleticEventDTO> athleticEvents = new List<AthleticEventDTO>();
            athleticEvents = athleticAL.GetAthleticEvents().ToList();

            var levelNames = (from m in allAthleticData where correctedQueryString.Contains(m.LevelName) select m).ToList();

            var ageDivisions = (from o in athleticEvents where correctedQueryString.Contains(o.AgeDivision) select o).ToList();

            var evntsCategory = (from n in athleticEvents where correctedQueryString.Contains(n.EventCategory ) select n).ToList();

            if (levelNames.Count != 0)
            {
                foreach (string level in levelNames.Select(a => a.LevelName))
                {
                    allAthleticData = athleticAL.GetAthleticDataByYearByLevelByAgeGruopByEvent(0,level,"","").ToList();
                }
                selectedCategory = "Level";
            }

            if (ageDivisions.Count != 0)
            {
                foreach (string dvsn in ageDivisions.Select(a => a.AgeDivision))
                {
                    allAthleticData = athleticAL.GetAthleticDataByYearByLevelByAgeGruopByEvent(0,"",dvsn,"").ToList().ToList();
                }
                selectedCategory = "Division";
            }
            if (evntsCategory.Count != 0)
            {
                foreach (string evnt in evntsCategory.Select(a => a.EventCategory))
                {
                    allAthleticData = athleticAL.GetAthleticDataByYearByLevelByAgeGruopByEvent(0,"","",evnt).ToList();
                }
                selectedCategory = "Event";
            }



            // get the total rows 
            double totalRows = 0;
            //double totalDelayRows = 0;
           // double totalNonDelayRows = 0;
            //foreach (AthleticDataDTO athDtaDTO in allAthleticData)
           // {
                //If it's relay total no of rows = no of rows in normal events + no of rows for 
               // if (athleticAL.isRelay(athDtaDTO.AthleticEventId))
               // {
                //    totalDelayRows++;
               // }
               // else
               // {
                //    totalNonDelayRows++;
               // }
           // }
            //totalRows = totalNonDelayRows + totalDelayRows / 4;
            totalRows = allAthleticData.Count;

            //lblAllAthleticPage.Text = "Displaying all of the College athletic Data - Page ";
            //lblAllAthleticOf.Text = "  of  ";

            if (queryString == "")
            {
                lblAllAthleticPage.Text = "";
                lblAllAthleticOf.Text = "";
                lblAllAthleticTotalPage.Text = "";
                lblAllAthleticCurrPage.Text = "";
                btnAllAthleticFirst.Visible = false;
                btnAllAthleticPrev.Visible = false;
                btnAllAthleticNext.Visible = false;
                btnAllAthleticLast.Visible = false;

            }
            else
            {
                lblAllAthleticPage.Text = "Displaying all of the College athletic Data - Page ";
                lblAllAthleticOf.Text = "  of  ";
                lblAllAthleticTotalPage.Text = CalculateTotalPages(totalRows).ToString();
                lblAllAthleticCurrPage.Text = currentPageNumber.ToString();
                btnAllAthleticFirst.Visible = true;
                btnAllAthleticPrev.Visible = true;
                btnAllAthleticNext.Visible = true;
                btnAllAthleticLast.Visible = true;
            }

            //lblAllAthleticTotalPage.Text = CalculateTotalPages(totalRows).ToString();
            int totalPageNumber = lblAllAthleticTotalPage.Text =="" ? 0: Convert.ToInt32(lblAllAthleticTotalPage.Text);
            //lblAllAthleticCurrPage.Text = currentPageNumber.ToString();

            if (totalPageNumber == 1)
            {
                if (currentPageNumber == 1)
                {
                    btnAllAthleticFirst.Enabled = false;
                    btnAllAthleticPrev.Enabled = false;
                    btnAllAthleticNext.Enabled = false;
                    btnAllAthleticLast.Enabled = false;
                    allAthleticDataOfOnePage = allAthleticData;
                }

            }
            else if (totalPageNumber > 1)
            {
                if (currentPageNumber == 1)
                {
                    btnAllAthleticFirst.Enabled = false;
                    btnAllAthleticPrev.Enabled = false;
                    btnAllAthleticNext.Enabled = true;
                    btnAllAthleticLast.Enabled = true;
                    allAthleticDataOfOnePage = allAthleticData.GetRange(0, PAGE_SIZE );
                }
                else if (currentPageNumber < totalPageNumber && currentPageNumber > 1)
                {
                    btnAllAthleticFirst.Enabled = true;
                    btnAllAthleticPrev.Enabled = true;
                    btnAllAthleticNext.Enabled = true;
                    btnAllAthleticLast.Enabled = true;
                    allAthleticDataOfOnePage = allAthleticData.GetRange(((currentPageNumber -1 ) * PAGE_SIZE)  , PAGE_SIZE );

                }
                else if (currentPageNumber == totalPageNumber)
                {
                    btnAllAthleticFirst.Enabled = true;
                    btnAllAthleticPrev.Enabled = true;
                    btnAllAthleticNext.Enabled = false;
                    btnAllAthleticLast.Enabled = false;
                    allAthleticDataOfOnePage = allAthleticData.GetRange(((currentPageNumber - 1) * PAGE_SIZE) , (allAthleticData.Count - (currentPageNumber - 1) * PAGE_SIZE));
                }
            }
            

            

            // gvAllMeeting.DataSource = allMeetingsOfOnePage;
            // gvAllMeeting.DataBind();

            CreateDynamicTable(allAthleticDataOfOnePage, selectedCategory);


        }

        private int CalculateTotalPages(double totalRows)
        {
            int totalPages = (int)Math.Ceiling(totalRows / (PAGE_SIZE));

            return totalPages;
        }

        protected void ChangePage(object sender, CommandEventArgs e)
        {

            switch (e.CommandName)
            {

                case "First":
                    currentPageNumber = 1;
                    break;

                case "Previous":
                    currentPageNumber = Int32.Parse(lblAllAthleticCurrPage.Text) - 1;
                    break;

                case "Next":
                    currentPageNumber = Int32.Parse(lblAllAthleticCurrPage.Text) + 1;
                    break;
                case "Last":
                    currentPageNumber = Int32.Parse(lblAllAthleticTotalPage.Text);
                    break;
            }


            BindData();
        }


        private void CreateDynamicTable(List<AthleticDataDTO> allAthleticDatasOfOnePage, string selectedCategory)
        {
            PlaceHolder4.Controls.Clear();

            // Fetch the number of Rows and Columns for the table 
            // using the properties





            int tblRows = allAthleticDatasOfOnePage.Count;



            // Create a Table and set its properties 
            Table tbl = new Table();
            tbl.Width = new Unit("100%");
            tbl.BorderStyle = BorderStyle.Solid;
            // Add the table to the placeholder control
            PlaceHolder4.Controls.Add(tbl);

            TableRow trHeader = new TableRow();
            trHeader.Width = new Unit("25%");
            HyperLink hlAthleticCellHeaderYear = new HyperLink();
            hlAthleticCellHeaderYear.Text = "Year";

            HyperLink hlAthleticCellHeaderLevel = new HyperLink();
            hlAthleticCellHeaderLevel.Text = "Level Name";

            HyperLink hlAthleticCellHeaderDivision = new HyperLink();
            hlAthleticCellHeaderDivision.Text = "Age Division";


            HyperLink hlAthleticCellHeaderEvent = new HyperLink();
            hlAthleticCellHeaderEvent.Text = "Event Category";


            HyperLink hlAthleticCellHeaderMore = new HyperLink();
            hlAthleticCellHeaderMore.Text = "Detail";
            //hlCompetitionCellHeaderMore.BackColor = System.Drawing.Color.DarkSlateBlue;
            //hlCompetitionCellHeaderMore.ForeColor = System.Drawing.Color.White;
            List<HyperLink> allHeaderHyperlinks = new List<HyperLink>();

            //based  on selected type change column orders
            switch (selectedCategory)
            {
                case "Year":

            allHeaderHyperlinks.Add(hlAthleticCellHeaderYear);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderLevel);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderDivision);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderEvent);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderMore);
                    break;

                case "Level":

            allHeaderHyperlinks.Add(hlAthleticCellHeaderLevel);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderYear);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderDivision);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderEvent);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderMore);
                    break;

                case "Division":

            allHeaderHyperlinks.Add(hlAthleticCellHeaderDivision);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderYear);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderLevel);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderEvent);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderMore);
                    break;

                case "Event":

            allHeaderHyperlinks.Add(hlAthleticCellHeaderEvent);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderYear);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderLevel);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderDivision);
            allHeaderHyperlinks.Add(hlAthleticCellHeaderMore);
                    break;
            }






            foreach (HyperLink hyperlinkHeader in allHeaderHyperlinks)
            {
                TableCell tcHeader = new TableCell();
                tcHeader.BackColor = System.Drawing.Color.DarkSlateBlue;
                tcHeader.ForeColor = System.Drawing.Color.White;

                tcHeader.Controls.Add(hyperlinkHeader);
                trHeader.Cells.Add(tcHeader);



            }

            tbl.Rows.Add(trHeader);
            

            // Now iterate through the table and add your controls 
            for (int i = 0; i < tblRows; i++)
            {
                TableRow tr = new TableRow();
                tr.Width = new Unit("25%");

                HyperLink hlAthleticCellYear = new HyperLink();
                hlAthleticCellYear.Text = allAthleticDatasOfOnePage[i].Year.ToString();

                HyperLink hlAthleticCellLevel = new HyperLink();
                hlAthleticCellLevel.Text = allAthleticDatasOfOnePage[i].LevelName.ToString();

                HyperLink hlAthleticCellDivision = new HyperLink();
                Guid athleticEventId = allAthleticDatasOfOnePage[i].AthleticEventId;

                List<AthleticEventDTO> athleticEvent = athleticAL.GetAthleticEventById(athleticEventId);
                hlAthleticCellDivision.Text = athleticEvent[0].AgeDivision;

                HyperLink hlAthleticCellEvent = new HyperLink();
                hlAthleticCellEvent.Text = athleticEvent[0].EventCategory;

                HyperLink hlAthleticCellMore = new HyperLink();
                hlAthleticCellMore.Text = "View More";


                queryString = Request.QueryString.ToString();



                if (selectedCategory == "Year")
                {
                    int selectdYear;
                    bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlAthleticCellMore.NavigateUrl = "viewAthleticDataById.aspx?" + "SelectedAthleticEventId=" + allAthleticDatasOfOnePage[i].AthleticEventId + "&SelectedYear=" + sportsUtil.encryptQueryStrings(allAthleticDatasOfOnePage[i].Year.ToString());
                }

                if (selectedCategory == "Division")
                {
                    //int selectdYear;
                    //bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlAthleticCellMore.NavigateUrl = "viewAthleticDataById.aspx?" + "SelectedAthleticEventId=" + allAthleticDatasOfOnePage[i].AthleticEventId + "&SelectedYear=" + sportsUtil.encryptQueryStrings(allAthleticDatasOfOnePage[i].Year.ToString());
                }

                if (selectedCategory == "Event")
                {
                    // int selectdYear;
                    //bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlAthleticCellMore.NavigateUrl = "viewAthleticDataById.aspx?" + "SelectedAthleticEventId=" + allAthleticDatasOfOnePage[i].AthleticEventId + "&SelectedYear=" + sportsUtil.encryptQueryStrings(allAthleticDatasOfOnePage[i].Year.ToString());
                }

                if (selectedCategory == "Level")
                {
                    // int selectdYear;
                    //bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlAthleticCellMore.NavigateUrl = "viewAthleticDataById.aspx?" + "SelectedAthleticEventId=" + allAthleticDatasOfOnePage[i].AthleticEventId + "&SelectedYear=" + sportsUtil.encryptQueryStrings(allAthleticDatasOfOnePage[i].Year.ToString());
                }





                List<HyperLink> allHyperlinks = new List<HyperLink>();

                switch (selectedCategory)
                {
                    case "Year":

                        allHyperlinks.Add(hlAthleticCellYear);
                        allHyperlinks.Add(hlAthleticCellLevel);
                        allHyperlinks.Add(hlAthleticCellDivision);
                        allHyperlinks.Add(hlAthleticCellEvent);
                        allHyperlinks.Add(hlAthleticCellMore);
                        break;

                    case "Level":

                        allHyperlinks.Add(hlAthleticCellLevel);
                        allHyperlinks.Add(hlAthleticCellYear);
                        allHyperlinks.Add(hlAthleticCellDivision);
                        allHyperlinks.Add(hlAthleticCellEvent);
                        allHyperlinks.Add(hlAthleticCellMore);
                        break;

                    case "Division":

                        allHyperlinks.Add(hlAthleticCellDivision);
                        allHyperlinks.Add(hlAthleticCellYear);
                        allHyperlinks.Add(hlAthleticCellLevel);
                        allHyperlinks.Add(hlAthleticCellEvent);
                        allHyperlinks.Add(hlAthleticCellMore);
                        break;

                    case "Event":

                        allHyperlinks.Add(hlAthleticCellEvent);
                        allHyperlinks.Add(hlAthleticCellYear);
                        allHyperlinks.Add(hlAthleticCellLevel);
                        allHyperlinks.Add(hlAthleticCellDivision);
                        allHyperlinks.Add(hlAthleticCellMore);
                        break;
                }
               

                foreach (HyperLink hyperlink in allHyperlinks)
                {
                    TableCell tc = new TableCell();



                    if (i % 2 == 0)
                    {
                        tc.Style.Add("background-color", "White");
                        tc.ForeColor = System.Drawing.Color.Blue;
                    }
                    else
                    {
                        tc.Style.Add("background-color", "#003399");
                        tc.ForeColor = System.Drawing.Color.White;

                    }



                    // Add the control to the TableCell
                    tc.Controls.Add(hyperlink); 


                    // Add the TableCell to the TableRow
                    tr.Cells.Add(tc);
                }

                // Add the TableRow to the Table

                tbl.Rows.Add(tr);
            }

            // This parameter helps determine in the LoadViewState event,
            // whether to recreate the dynamic controls or not

            ViewState["dynamictable"] = true;
        }
    }
}